using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

using MT.eVotePRS.Common;
using MT.eVotePRS.Device;
using MT.eVotePRS.Model;

namespace MT.eVotePRS.UI
{
    public partial class frmHandsetMaint : Form
    {
        InventoryTable inventoryTbl;
        InventoryTxn inventoryTxn;

        public frmHandsetMaint()
        {
            InitializeComponent();

            inventoryTbl = new InventoryTable();
            inventoryTxn = new InventoryTxn();

            IList<Status> statusList = new List<Status>();
            statusList.Add(Presentation.Util.Constants.Status_Nil);
            statusList.Add(Presentation.Util.Constants.Status_CheckOut);
            statusList.Add(Presentation.Util.Constants.Status_CheckIn);
            statusList.Add(Presentation.Util.Constants.Status_Lost);
            statusList.Add(Presentation.Util.Constants.Status_Fault);
            statusList.Add(Presentation.Util.Constants.Status_Found);
            statusList.Add(Presentation.Util.Constants.Status_Repaired);
            statusList.Add(Presentation.Util.Constants.Status_FoundnFault);

            cmbBoxStatus.DataSource = statusList;
            cmbBoxStatus.DisplayMember = "StatusDesc";
        }

        protected override void WndProc(ref Message m)
        {
            int devCount;

            if (m.Msg == Device.Native.Win32Message.WM_DEVICECHANGE)
            {
                switch ((int)m.WParam)
                {
                    case Device.Native.Win32Message.DBT_DEVICEARRIVAL:
                    case Device.Native.Win32Message.DBT_DEVICEREMOVECOMPLETE:

                        devCount = Program.ArsAPIHelper.ArsDeviceConnected();

                        if (0 == devCount)
                        {
                            if (Program.ArsAPIHelper.Processing)
                            {
                                Program.ArsAPIHelper.StopProcess();
                            }
                            DialogBox.boxWarning(string.Format("Receiver Count={0}, Please prepare the receiver first.", devCount.ToString()), "Warning!");
                        }
                        Thread.Sleep(10);
                        break;
                    default:
                        break;
                }
            }
            base.WndProc(ref m);
        }

        private void frmHandsetMaint_Load(object sender, EventArgs e)
        {
            txtDatetime.Text = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");

            // Since we are start this program, it would like to detect the device once.
            Message m = new Message();
            m.Msg = Device.Native.Win32Message.WM_DEVICECHANGE;
            m.WParam = (System.IntPtr)Device.Native.Win32Message.DBT_DEVICEARRIVAL;

            WndProc(ref m);

            int ret = Program.ArsAPIHelper.RegisterDeviceNotify((Int32)this.Handle);
            if (ret > 0)
            {
                Program.ArsAPIHelper.StartProcess();
            }

            txtHandsetID.Focus();
            txtHandsetID.SelectAll();

            timer1.Start();
        }

        private void frmHandsetMaint_FormClosing(object sender, FormClosingEventArgs e)
        {
            Program.ArsAPIHelper.StopProcess();
            Program.ArsAPIHelper.UnRegisterDeviceNotify();        
        }
  
        private void timer1_Tick(object sender, EventArgs e)
        {
            txtDatetime.Text = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            if ( !string.IsNullOrEmpty( txtHandsetID.Text ))
            {
                if (DialogBox.boxConfirmNo("Are you sure to abort the current action?") == DialogResult.No)
                    return;
            }

            this.Close();
            this.Dispose();
        }

        private bool IsValidate()
        {
            bool ret = true;
            // student id
            if (string.IsNullOrEmpty(txtHandsetID.Text.Trim()))
            {
                DialogBox.boxWarning("Invalid Handset ID!", "Warning!");
                txtHandsetID.SelectAll();
                return false;
            }
            return ret;
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            if (!IsValidate())
                return;
            // 1. check if the handset id in the InventoryTable or not

            // 2. Save this override record into InventoryEvents
            object status = cmbBoxStatus.SelectedItem;
            if (status == null)
            {
                DialogBox.boxWarning("Select a status for the handset.", "Warning!");
                return;
            }
              

            Status handsetStatus = (Status)status;

            inventoryTxn = new InventoryTxn();
            inventoryTxn.HandsetID = txtHandsetID.Text;
            inventoryTxn.StudentID = string.Empty;
            inventoryTxn.TxnTime = DateTime.Now;
            inventoryTxn.Status = handsetStatus.Id;
            inventoryTxn.UserEvent = handsetStatus.StatusDesc;
            inventoryTxn.PaymentNo = string.Empty;
            inventoryTxn.NeedPay = false;
            inventoryTxn.Remark = txtRemark.Text;
            inventoryTxn.IsOverride = true;
            inventoryTxn.OverrideStatus = handsetStatus.Id;

            object objTxnId = new Presentation.Logic.InventoryTxnActions().CreateNewTxn(inventoryTxn);

            if (objTxnId != null && Convert.ToInt32(objTxnId) > 1)
            {
                DialogBox.boxInfo("Completed!");
            }
            else
            {
                DialogBox.boxWarning("Failed!");
            }
        }

        private void txtHandsetID_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string handsetId = txtHandsetID.Text.Trim();
                if (string.IsNullOrEmpty(handsetId) || handsetId.Length < Constants.LEN_ID_Min || !Common.Helper.Helper.IsNumeric(handsetId))
                {
                    DialogBox.boxWarning("Invalid Handset ID!", "Warning!");
                    txtHandsetID.SelectAll();
                    return;
                }
            }
        }

        delegate void _dataReceived(object sender, ARSEventArgs e);
        void dataReceiver_DataReceived(object sender, ARSEventArgs e)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new _dataReceived(dataReceiver_DataReceived), sender, e);
                return;
            }

            HandsetData keypadData = (HandsetData)e.ReceivedData;
            switch (keypadData.CommandCode)
            {
                case ARSCommandCode.STUDENT_JOIN:
                    txtHandsetID.Text = keypadData.MacStr;
                    break;

                default:
                    break;
            }
        }
    }
}